package com.taxinfo.component;

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.util.Duration;

public class DynamicScrollingNotificationPane extends ScrollPane {

    private final HBox notificationContainer = new HBox();
    private final Timeline timeline = new Timeline();
    private double scrollSpeed = 1.0; // 滚动速度

    public DynamicScrollingNotificationPane() {
        super();
        init();
    }

    private void init() {
        // 设置HBox为notificationContainer的子节点
        setContent(notificationContainer);
        setHbarPolicy(ScrollBarPolicy.NEVER);
        setVbarPolicy(ScrollBarPolicy.NEVER);

        // 设置HBox的对齐方式和间距
        notificationContainer.setAlignment(Pos.CENTER_LEFT);
        notificationContainer.setSpacing(5);
        HBox.setHgrow(notificationContainer, Priority.ALWAYS);

        // 初始化滚动动画
        KeyFrame keyFrame = new KeyFrame(Duration.millis(50), event -> {
            if (notificationContainer.getTranslateX() < 0) {
                double newTranslateX = notificationContainer.getTranslateX() + scrollSpeed;
                notificationContainer.setTranslateX(newTranslateX);
            } else {
                // 如果已经滚动到最左边，重置位置
                notificationContainer.setTranslateX(0);
                timeline.stop();
            }
        });
        timeline.setCycleCount(Timeline.INDEFINITE);
        timeline.getKeyFrames().add(keyFrame);
    }

    public void addNotification(Node notification) {
        notificationContainer.getChildren().add(notification);
        // 每添加一个通知，重新计算布局
        requestLayout();
        // 如果动画正在运行，停止然后重新开始
        if (timeline.getStatus() == Animation.Status.RUNNING) {
            timeline.stop();
        }
        timeline.play();
    }

    public double getScrollSpeed() {
        return scrollSpeed;
    }

    public void setScrollSpeed(double scrollSpeed) {
        this.scrollSpeed = scrollSpeed;
    }
}
